<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Sun, SunMoon } from 'lucide-vue-next'
import { Button } from '@/components/ui/button'

// 主题类型定义
type Theme = 'light' | 'dark'

// 响应式主题状态，默认为白天模式
const isDark = ref(false)

// 应用主题到DOM
const applyTheme = (dark: boolean) => {
  const html = document.documentElement
  const body = document.body
  
  // 移除所有主题类
  html.classList.remove('dark', 'light')
  body.classList.remove('dark', 'light')
  
  isDark.value = dark
  
  if (dark) {
    html.classList.add('dark')
    body.classList.add('dark')
    html.setAttribute('data-theme', 'dark')
  } else {
    html.classList.add('light')
    body.classList.add('light')
    html.setAttribute('data-theme', 'light')
  }
}

// 切换主题
const toggleTheme = () => {
  const newTheme = !isDark.value
  applyTheme(newTheme)
  localStorage.setItem('theme', newTheme ? 'dark' : 'light')
}

// 组件挂载时初始化
onMounted(() => {
  // 从localStorage读取保存的主题，默认为light
  const savedTheme = localStorage.getItem('theme') as Theme
  const initialTheme = savedTheme || 'light'
  
  applyTheme(initialTheme === 'dark')
})
</script>

<template>
  <Button 
    variant="ghost" 
    size="icon" 
    @click="toggleTheme"
    class="relative"
  >
    <!-- 根据当前主题显示对应图标 -->
    <Sun 
      v-if="!isDark" 
      class="h-[1.2rem] w-[1.2rem] transition-all duration-300" 
    />
    <SunMoon 
      v-else 
      class="h-[1.2rem] w-[1.2rem] transition-all duration-300" 
    />
    <span class="sr-only">切换主题</span>
  </Button>
</template>

<style scoped>
/* 确保过渡效果平滑 */
.transition-all {
  transition-property: all;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 300ms;
}
</style>